package com.crazy.index.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.crazy.index.domain.User;
import com.crazy.index.domain.house.HousePicture;
import com.crazy.index.domain.order.Order;
import com.crazy.index.domain.po.HousePo;
import com.crazy.index.service.composite.IntegrationService;
import com.crazy.index.service.house.HouseService;
import com.crazy.index.service.user.UserService;

@Controller
@RequestMapping("/house")
public class HouseController {
//
@Autowired
private IntegrationService integrationService;
@Autowired
private HouseService houseService;
@Autowired
private UserService userService;

@RequestMapping("/queryHouses.do")


public  ModelAndView  queryHouses(){
	
	List<HousePo> querys = houseService.querys(1, new HousePo());
	
	Map<Integer, HousePicture> haMap=new HashMap<>();
	
	ModelAndView modelAndView=new ModelAndView("/index");
	Map map=new HashMap<>();
	for(HousePo h:querys){
		
		if(h!=null){
		
		List<HousePicture> queryPictures = houseService.queryPictures(h.getId());
		
		map.put(h.getId(), queryPictures.size());
		if(queryPictures!=null&&queryPictures.size()>0){
			haMap.put(h.getId(), queryPictures.get(0));
			}
		}
		
	}
	modelAndView.addObject("houses", querys);
	
	modelAndView.addObject("pictures", haMap);
	
	modelAndView.addObject("picturesSize",map);
	
	return modelAndView;
	
	}
	@RequestMapping("/renting.htm")
	public String Renting(@RequestParam("houseId")Integer houseId,ModelMap map){
		
		HousePo queryHouse = houseService.queryHouse(houseId);	
		List<HousePicture> queryPictures = houseService.queryPictures(houseId);
		map.put("house",queryHouse);
		map.put("imgs", queryPictures);
		/*System.out.println(queryHouse);
		System.out.println(queryPictures);*/
		
		return "/house/renting";
	}
	@RequestMapping("/renting.do")
	public String Renting(Integer houseId,Integer count,HttpServletRequest request,ModelMap  map){
		User user =(User)request.getSession().getAttribute("USER");
		
		Order hireHouse = integrationService.hireHouse(houseId, user.getId(), count, true);
		
		request.getSession().setAttribute("USER",userService.queryById(user.getId()));
		
		return "/renting";
	}
	
}
